extends Node

## 加载的玩家数据 [br]
## value：类型 Array[PlayerResource]
var _squads: Dictionary[String, Array]


func _init():
	_load_from_json()


func _load_from_json():
	var file := FileAccess.open(GlobalConstants.SQUADS_JSON_FILE, FileAccess.READ)
	if not file:
		printerr("cannot open squads.json: ", FileAccess.get_open_error())
		return
	var file_content := file.get_as_text()
	file.close()

	var json := JSON.new()
	var res := json.parse(file_content)
	if res != Error.OK:
		printerr("Cannot parse json: ", json.get_error_line(), " - ",  json.get_error_message())
		return
	_fill_squads(json)


func _fill_squads(json: JSON):
	for team in json.data:
		var country_name := team["country"] as String
		var players := team["players"] as Array

		var player_resources :Array = _squads[country_name] if _squads.has(country_name) else []
		for player in players:
			var player_res:= PlayerResource.new()
			player_res.full_name = player["name"] as String
			player_res.country = country_name
			player_res.player_skin = player["skin"] as Player.PlayerSkin
			player_res.player_role = player["role"] as Player.PlayerRole
			player_res.speed = player["speed"] as float
			player_res.power = player["power"] as float
			player_resources.append(player_res)

		# 球员的数量必须是6个
		assert(player_resources.size() == 6)

		_squads[country_name] = player_resources



## 获取球队，返回的真实类型是 Array[PlayerResource]
func get_squad(country: String) -> Array:
	if _squads.has(country):
		return _squads[country]
	return []
